/*
 * @Author: tianlun
 * @Date: 2025-08-21 22:29:10
 * @LastEditTime: 2025-08-21 23:58:43
 */
import { Content, Page } from '@alita/flow';
import { setPageNavBar, useLocation, useModel, useNavigate } from 'alita';
import { AutoCenter, DotLoading, Modal, Space } from 'antd-mobile';
import * as echarts from 'echarts';
import { useEffect, useRef, useState } from 'react';
import { Action } from 'antd-mobile/es/components/modal/modal-action-button';
import DateSelectPopup, {
  ComplexDateSelectedValue,
  DateDefaultValue,
} from '@/components/date-range-selector';
import { DetailResult } from '@/pages/types/type';
import { checkAuthorize } from '@/utils/authorize';
import { postRequestInit, urlPrefix } from '@/utils/http';
import Toast, { ToastHandler } from 'antd-mobile/es/components/toast';
import './index.less';
import { DownCircleOutline, DownlandOutline } from 'antd-mobile-icons';

declare type HospitalStatsReponse = {

  clinicalDepartmentCount: number;
  clinicalDepartments: { id: number; name: number }[];
  count: number;
  deviceCount: number;
  doctorCount: number;
  doctors: { value: number; label: number }[];
  livingTypeStandards: { value: number; label: number }[];
  timeoutCount: number;
  timeoutStats: { value: number; label: number }[];
  totalPrice: number;
  workingModes: { value: number; label: number }[];
  groupedDoctors: {
    value: number;
    label: number;
    children: { value: number; label: number }[];
  }[];
  groupedPrices: {
    value: number;
    label: number;
    children: { value: number; label: number }[];
  }[];
  groupedWorkingModes: {
    value: number;
    label: number;
    children: { value: number; label: number }[];
  }[];
  countItems: { tab: { label: string; value: string; }, count: number,color:string }[],
  dateGroupUnit: { value: string, label: string };
  twoLevelWorkingModes: {
    value: number;
    label: number;
    children: { value: number; label: string }[];
  }[];
};

const HospitalManage: React.FC = () => {
  const location = useLocation();
  const [tokening, setTokening] = useState<boolean>(true);
  const [tokenFail, setTokenFail] = useState<string | undefined>(undefined);
  const [authOK, setAuthOK] = useState<boolean>(false);
  const [stats, setStats] = useState<HospitalStatsReponse>();

  const [dateRange, setDateRange] = useState<ComplexDateSelectedValue>({
    ...DateDefaultValue, lastClick: 'preDefine', preDefine: 'currentMonth', sideBarKey: "preDefine", tip: '本月'
  });

  const [showDatePicker, setShowDatePicker] = useState<boolean>(false);
  const navigate = useNavigate();
  useEffect(() => {
    setPageNavBar({
      pagePath: location.pathname,
      navBar: {
        hideNavBar: true,
        pageTitle: `医院`,
        pageBackground: '#eee',
      },
    });
  }, []);

  const model = useModel('useAuthModel');
  useEffect(() => {
    checkAuthorize(
      (x) => setTokening(x),
      (y) => {
        console.log(`token检查完成，是否通过授权：${y}`);
        setAuthOK(y);
      },
      (z) => setTokenFail(z),
      model,
    );
  }, []);

  const handler = useRef<ToastHandler>();



  useEffect(() => {
    if (authOK) {
      handler.current = Toast.show({
        icon: 'loading',
        content: '正在统计',
        maskClickable: false,
        duration: 0,
      });
      fetch(
        `${urlPrefix}/api/study-stats/stats-for-hospital`,
        postRequestInit({
          hospitals: model.userInfo.manageHospitals.map((h) => h.id),
          dateRange,
        }),
      )
        .then(async (rsp: Response) => {
          if (rsp.ok) {
            await rsp
              .json()
              .then(
                ({ data, code, msg }: DetailResult<HospitalStatsReponse>) => {
                  if (code === 0) {
                    if (data) {
                      console.log(data);
                      setStats(data!);
                    } // end if data

                    handler.current?.close();
                  } else {
                    Toast.show({
                      icon: 'fail',
                      content: msg,
                      duration: 3000,
                    });
                  }
                },
              )
              .catch((reason) => {
                Toast.show({
                  icon: 'fail',
                  content: `加载失败：${reason}`,
                });
              });
          }
        })
        .catch((reason: any) => {
          console.error(reason);
          Toast.show({
            icon: 'fail',
            content: `加载失败：${reason}`,
          });
        })
        .finally(() => { });
    } // end if authOK
  }, [authOK, dateRange]);

  const workingModeBarRef = useRef(null);
  const doctorPieRef = useRef(null);

  const twoLevelWorkingModesRef = useRef(null);

  useEffect(() => {
    if (!workingModeBarRef.current || !stats) {
      return;
    }

    const chart = echarts.init(workingModeBarRef.current);
    const { groupedWorkingModes } = stats;
    const line1 = [
      'wm',
      ...(groupedWorkingModes[0]?.children.map((sy) => sy.label) || []),
    ];
    const option = {
      legend: {},
      tooltip: {},
      dataset: {
        source: [
          line1,
          ...groupedWorkingModes.map((gwm) => [
            gwm.label,
            ...gwm.children.map((c) => c.value),
          ]),
        ],
      },

      xAxis: { type: 'category' },
      yAxis: {},
      // Declare several bar series, each will be mapped
      // to a column of dataset.source by default.
      series: [{
        type: 'bar', itemStyle: {
          color: '#ff3141'
        }
      }, { type: 'bar' }, { type: 'bar' }],
    };

    chart.setOption(option);
    // 注意：这里需要返回一个清理函数，以确保在组件卸载时销毁ECharts实例
    return () => {
      chart.dispose();
    };
  }, [stats]);


  // 绘制，模式，检查结果柱状图
  useEffect(() => {
    if (!twoLevelWorkingModesRef.current || !stats) {
      return;
    }

    const chart = echarts.init(twoLevelWorkingModesRef.current);
    const { twoLevelWorkingModes: rawData } = stats;

    const serKeysAll: { value: string, color: string }[] = [{ value: '正常', color: '#00b578' },
    { value: '异常', color: '#ff8f1f' },
    { value: '危急', color: '#ff3141' }];
    const serKeys = serKeysAll.filter(({ value }) => rawData.some(c => c.children.some(ci => ci.label === value)))

    const option = {

      tooltip: {
        trigger: 'axis',
        // axisPointer: {
        //   type: 'cross',
        //   crossStyle: {
        //     color: '#999'
        //   }
        // }
      },

      // toolbox: {
      //   feature: {
      //     dataView: { show: true, readOnly: false },
      //     magicType: { show: true, type: ['line', 'bar'] },
      //     restore: { show: true },
      //     saveAsImage: { show: true }
      //   }
      // },
      legend: {
        data: serKeys.map(ski => ski.value)
      },
      xAxis: [
        {
          type: 'category',
          data: rawData.map(rd => rd.label),
          axisPointer: {
            type: 'shadow'
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          //name: 'counting81Hex',
          min: 0,
          //max: 250,
          interval: 500,
          axisLabel: {
            formatter: '{value} 宗'
          }
        }
      ],

      series: serKeys.map(({ value: skey, color }) => ({
        name: skey,
        type: 'bar',
        tooltip: {
          valueFormatter: function (value: number) {
            return value + ' ml';
          }
        },
        itemStyle: {
           color
        },
        data: rawData.map(first => first.children).flat().filter(vl => vl.label === skey).map(vl => vl.value)//  [ 2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]
      })),

    };

    chart.setOption(option);
    chart.off('click');
    chart.on('click', function (params: echarts.ECElementEvent) {
      // params包含被点击柱子的信息
      console.log(params);
    });

    // 注意：这里需要返回一个清理函数，以确保在组件卸载时销毁ECharts实例
    return () => {
      chart.dispose();
    };

  }, [stats])

  useEffect(() => {
    if (!doctorPieRef.current || !stats) {
      return;
    }
    const chart = echarts.init(doctorPieRef.current);
    const option = {
      grid: {
        left: '1%',
        right: '1%',
        bottom: '1%',
        containLabel: true,
      },
      tooltip: {
        trigger: 'item',
      },
      //   legend: {
      //     orient: 'vertical',
      //     left: 'right',
      //   },
      series: [
        {
          name: '医生工作量',
          type: 'pie',
          radius: '50%',
          data: stats.doctors.map(({ value, label: name }) => ({
            value,
            name,
          })),
          label: {
            formatter: '{b}\n {c}份    ',
          },
          color: [
            '#7EC581',
            '#79B0E2',
            '#5087EC',
            '#ECC050',
            '#91c7ae',
            '#749f83',
          ], // 设置饼图颜色
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
        },
      ],
    };
    chart.setOption(option);
    // 注意：这里需要返回一个清理函数，以确保在组件卸载时销毁ECharts实例
    return () => {
      chart.dispose();
    };
  }, [stats]);

  function expertExcel() {
    handler.current = Toast.show({
      icon: 'loading',
      content: '正在生成Excel文件',
      maskClickable: false,
      duration: 0,
    });

    fetch(
      `${urlPrefix}/api/study-search/export-excel`,
      postRequestInit({
        imageAcquisitionDateValue: dateRange,
        hospitalIds: model.userInfo.manageHospitals.map(h => h.id),
        xTag: 'none'
      }),
    )
      .then(async (rsp: Response) => {
        if (rsp.ok) {
          await rsp
            .json()
            .then(async ({ data, code, msg }: DetailResult<string>) => {
              if (code === 0) {
                handler.current?.close();
                Modal.show({
                  title: '已导出',
                  closeOnAction: true,
                  actions: [
                    {
                      key: 'download',
                      text: (
                        <AutoCenter>
                          {' '}
                          <a href={data!} target="_blank" rel="noreferrer">
                            下载
                          </a>
                        </AutoCenter>
                      ),
                    },
                  ],
                  onAction: (action: Action, index: number) => {
                    console.log(action, ',index=', index);
                  },
                });
              } else {
                Toast.show({
                  icon: 'fail',
                  content: msg,
                  duration: 4000,
                });
              }
            })
            .catch((reason) => {
              Toast.show({
                icon: 'fail',
                content: `执行失败：${reason}`,
              });
            });
        }
      })
      .catch((reason: any) => {
        Toast.show({
          icon: 'fail',
          content: `执行失败：${reason}`,
        });
      })
      .finally(() => {
        //handler.current?.close();
      });
  }

  if (tokening || !stats) {
    return <DotLoading />;
  }
  const hospitals = model.userInfo.manageHospitals;
  const hospital = hospitals[hospitals.length - 1];
  const {
    totalPrice,
    count,
    timeoutCount,
    countItems,
    dateGroupUnit
  } = stats!;

  return (
    <Page>
      <Content>
        <div className="infoHospita">
          <div className="hospitaCount">
            <div className="countTitle">
              <div className="countYear">
                {hospitals.length <2 && <>{hospital.name}</>}
                {hospitals.length>=2 && <Space>{ hospitals.map( (h,index)=><span key={index}>{h.name}</span> ) }</Space> }
                </div>
              <div
                className="countMonth"
                onClick={() => setShowDatePicker(true)}
              >
                {dateRange.lastClick ? dateRange.tip : '申请时间'}
              </div>
            </div>
            <div className="infoStatistics">
              {countItems.map(({ tab, count, color }) => {
                return (<div className="countBG" key={tab.value} onClick={() => {
                  navigate(`/study/search?xTag=${tab.value}`);
                }}>
                  <div style={{
                    'color': `var(--adm-badge-color, var(--adm-color-${count <= 0 ? 'weak' : color === 'default' ? 'success' : color
                      }))`,
                  }} >{count}</div>
                  <div className="infoLabel">{tab.label}</div>
                </div>)
              })}

              {/* <div className="countBG" onClick={() => {
                navigate(`/study/search`)
              }}>
                <div className={'count'}>{count}</div>
                <div className="infoLabel">总数</div>
              </div>

              <div className="countBG">
                <div className={'overtime'}>{timeoutCount}</div>
                <div className="infoLabel">超时</div>
              </div>

              <div className="countBG">
                <div className={'diagnosed'}>{countItems.filter(({ tab: { value } }) => value === 'waitingDiagnosis')[0]?.count}</div>
                <div className="infoLabel">待处理</div>
              </div>

              <div className="countBG">
                <div className={'diagnosed'}>{countItems.filter(({ tab: { value } }) => value === 'handling')[0]?.count}</div>
                <div className="infoLabel">处理中</div>
              </div>

              <div className="countBG">
                <div className={'reviewed'}>{countItems.filter(({ tab: { value } }) => value === 'audited')[0]?.count}</div>
                <div className="infoLabel">已审核</div>
              </div> */}

            </div>
          </div>

          <div className="hospitalBar" style={{ height: '4.5rem' }}>
            <div className="infoTitle">医生工作量 <DownlandOutline onClick={expertExcel} /></div>
            <div className="infoChart" ref={doctorPieRef}></div>
          </div>

          <div className="hospitalBar">
            <div className="infoTitle" >按来源统计(按{dateGroupUnit.label})
              <DownlandOutline onClick={expertExcel} />
            </div>
            <div className="infoChart" ref={workingModeBarRef}></div>
          </div>

          <div className="hospitalBar">
            <div className="infoTitle" >诊断结果统计</div>
            <div className="infoChart" ref={twoLevelWorkingModesRef}></div>
          </div>
        </div>



        <DateSelectPopup
          visable={showDatePicker}
          dateSelectedValue={dateRange}
          hide={setShowDatePicker}
          setDateSelectedValue={setDateRange}
        />
      </Content>
    </Page>
  );
};



export default HospitalManage;
